<template>
    <div>
      <el-dialog
          title="新增嘉宾"
          :visible.sync="addAuthorDia"
          width="800px"
          center
          append-to-body
          :close-on-click-modal="false"
        >
        <div class="author">
            <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="120px" class="demo-ruleForm">
        <el-form-item label="嘉宾姓名" prop="ifName">
          <el-input class="width500" v-model="ruleForm.ifName" placeholder="请输入嘉宾姓名"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="ifSex">
          <el-select class="width500" v-model="ruleForm.ifSex" placeholder="请选择性别">
            <el-option label="男" value="0"></el-option>
            <el-option label="女" value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="头像:" prop="img">
          <!-- 配合ruleForm校验 -->
          <el-select v-model="ruleForm.img[0]" style="display: none !important" />
          <el-upload
            ref="uploadPic"
            action="https://fileapi.instrument.com.cn/upflash/upimg.ashx?colname=webinar"
            list-type="picture-card"
            :file-list="dialogImageUrl"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            :limit="1">
            <i class="el-icon-plus"></i>
            <div slot="file" slot-scope="{file}">
              <img
                class="el-upload-list__item-thumbnail"
                :src="file.url" alt=""
              >
              <span class="el-upload-list__item-actions">
                <span
                  class="el-upload-list__item-delete"
                  @click="handleRemove(file)"
                >
                  <i class="el-icon-delete"></i>
                </span>
              </span>
            </div>
          </el-upload>
          <p class="hint">
            图片格式支持JPEG、BMP、GIF、PNG等
          </p>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageBigUrl" alt="">
          </el-dialog>
        </el-form-item>
        <el-form-item label="电子邮箱" prop="ifEmail">
          <el-input class="width500" v-model="ruleForm.ifEmail" placeholder="请输入电子邮箱"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="ifMobile">
          <el-input class="width500" v-model="ruleForm.ifMobile" placeholder="请输入手机号"></el-input>
        </el-form-item>
        <el-form-item label="单位名称" prop="ifCompany">
          <el-input class="width500" v-model="ruleForm.ifCompany" placeholder="请输入单位名称"></el-input>
        </el-form-item>
        <el-form-item label="职位" prop="job">
          <el-input class="width500" v-model="ruleForm.job" placeholder="请输入职位"></el-input>
        </el-form-item>
        <el-form-item label="熟悉仪器" prop="ssIdList">
          <el-cascader class="width500"
            ref="cascader"
            v-if="!loading"
            clearable
            placeholder="请选择熟悉仪器"
            v-model="ruleForm.ssIdList"
            :options="projectAllList"
            :props="propsConfig"
            filterable
            @change="handleCascaderChange"></el-cascader>

        </el-form-item>
        <el-form-item label="所属行业" prop="fdId1">
          <el-select class="width500" v-model="ruleForm.fdId1" placeholder="请选择所属行业" @change="getIndustrySectorSelect">
            <el-option
              v-for="item in industrySectorList"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="嘉宾简介" prop="infoHtml">
          <div style="width: 600px">
            <Ueditor ref="ue" :value="defaultMSG" @ready="editorReadyWap" />
          </div>
        </el-form-item>
      </el-form>
      </div>
      <div class="btm_butn" slot="footer">
          <el-button type="primary" @click="submitForm('ruleForm')">保存</el-button>
      </div>
        </el-dialog>
    </div>
  </template>
  
  <script>
  import api from '@/api/index'
import Ueditor from '@/components/UEditor'
import { getImShowId } from '@/utils/auth'
import { validateEmail, validateMobile } from '@/utils/validate'
  export default {
    components: { Ueditor },
  data(){
      return{
        loading: true,
      dialogImageUrl: [],
      dialogVisible: false, // 图片预览弹窗
      dialogImageBigUrl: '', // 预览图片
      defaultMSG: '',
      ruleForm: {
        adminID: getImShowId(),
        authorID: '', // 专家id
        ifName: '', // 专家姓名
        ifSex: null, // 性别
        img: '', // 专家头像
        ifEmail: '', // 电子邮箱
        ifMobile: '', // 手机号
        ifCompany: '', // 单位
        job: '', // 职位
        ssIdList: [], // 熟悉的仪器ssId集合
        ssId11: '', // 所熟悉的仪器一(一级)
        ssId12: '', // 所熟悉的仪器一(二级)
        ssId1: '', // 所熟悉的仪器一(三级)
        ifInterestinstrument11: '', // 所熟悉的仪器一(一级)名称
        ifInterestinstrument12: '', // 所熟悉的仪器一(二级)名称
        ifInterestinstrument1: '', // 所熟悉的仪器一(三级)名称
        fdId1: '', // 所熟悉的行业领域一
        ifSpecializefield1: '', // 所熟悉的行业领域一名称
        infoHtml: '', // 介绍（富文本）
        channel: 1, // 渠道（1-网络讲堂;2-我要测）
        type: 2 // 1-专家报告人；2-厂商报告人
      },
      rules: {
        ifName: [
          { required: true, message: '请输入专家姓名', trigger: 'blur' }
        ],
        ifSex: [
          { required: true, message: '请选择性别', trigger: 'change' }
        ],
        img: [
          { required: true, message: '请上传专家头像', trigger: 'change' }
        ],
        ifEmail: [
          { required: true, validator: validateEmail, trigger: 'blur' }
        ],
        ifMobile: [
          { required: true, validator: validateMobile, trigger: 'blur' }
        ],
        ifCompany: [
          { required: true, message: '请输入单位', trigger: 'blur' }
        ],
        job: [
          { required: true, message: '职位', trigger: 'blur' }
        ],
        ssIdList: [
          { required: true, message: '请选择熟悉仪器', trigger: 'blur' }
        ],
        fdId1: [
          { required: true, message: '请选择行业领域', trigger: 'change' }
        ],
        infoHtml: [
          { required: true, message: '请输入专家简介', trigger: 'change' }
        ]
      },
      addAuthorDia:false,
      projectAllList: [],
      industrySectorList: [],
      propsConfig: {
        lazy: true, // 此处必须为true
        lazyLoad: this.getInstrumentLazyLoad
      }
      }
  },
  created () {
    this.getDetail()
    // this.getInstrumentList(0) // 获取仪器联级 - 0一级
    this.getIndustryList() // 行业领域
  },
  methods: {
    getInstrumentLazyLoad (node, resolve) {
      if (!node) {
        return false
      }
      const { level } = node
      if (level >= 3) {
        node.loading = false
        node.loaded = true
        return false
      }

      // level代表当前点击选择哪一项，，比如0代表第一次进去加载数据，1是选择后的操作
      if (level === 0) {
        api.specialist.getPrincipleClassifySelectByLevel({ parentId: 0 }).then((res) => {
          if (res.code === 200) {
            resolve(
              res.data.data.map((val) => {
                return {
                  value: val.id,
                  label: val.name,
                  leaf: level >= 2
                }
              })
            )
          }
        })
      } else if (level === 1) {
        api.specialist.getPrincipleClassifySelectByLevel({ parentId: node.data.value }).then((res) => {
          if (res.code === 200) {
            resolve(
              res.data.data.map((val) => {
                return {
                  value: val.id,
                  label: val.name,
                  leaf: level >= 2
                }
              })
            )
          }
        })
      } else if (level === 2) {
        api.specialist.getPrincipleClassifySelectByLevel({ parentId: node.data.value }).then((res) => {
          if (res.code === 200) {
            resolve(
              res.data.data.map((val) => {
                return {
                  value: val.id,
                  label: val.name,
                  leaf: level >= 2
                }
              })
            )
          }
        })
      }
    },
    editorReadyWap (instance) {
      instance.setContent(this.ruleForm.infoHtml)
      instance.addListener('contentChange', () => {
        this.ruleForm.infoHtml = instance.getContent()
      })
    },
    submitForm (formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          this.ruleForm.imshowid = this.ruleForm.adminID
          await api.specialist.saveAuthor(this.ruleForm)
          this.$message.success('操作成功！')
          this.addAuthorDia=false
          this.$emit('renovate',true)
        } else {
          // console.log('error submit!!')
          return false
        }
      })
    },
    handleAvatarSuccess (res, file) {
      console.log(res,'22222');
      const imgUrl = `https://img1.17img.cn/17img/${res.url}`
      this.ruleForm.img = imgUrl
    },
    beforeAvatarUpload (file) {
      const isImgType = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/webp'
      // const isLt2M = file.size / 1024 / 1024 < 2

      if (!isImgType) {
        this.$message.error('上传头像图片只能是 JPG/Png 格式!')
      }
      return isImgType
    },
    async handleRemove (file) {
      this.dialogImageUrl = []
      this.ruleForm.img = ''
    },
    // 获取仪器1联级
    async getInstrumentList (id) {
      const params = {
        parentId: id
      }
      try {
        const { data } = await api.specialist.getPrincipleClassifySelectByLevel(params)
        this.projectAllList = data.data
        if (this.projectAllList.length > 0) {
          for (let i = 0; i < this.projectAllList.length; i++) {
            this.projectAllList[i].value = this.projectAllList[i].id
            this.projectAllList[i].label = this.projectAllList[i].name
          }
        }
      } catch (error) {
        this.projectAllList = []
      }
    },
    // 根据仪器id反查仪器名称
    async getInstrumentName (level, parentId, id) {
      const params = {
        parentId: parentId
      }
      try {
        const { data } = await api.specialist.getPrincipleClassifySelectByLevel(params)
        data.data.map(item => {
          if (level === 0) {
            if (item.id === id) { this.ruleForm.ifInterestinstrument11 = item.name }
          }
          if (level === 1) {
            if (item.id === id) { this.ruleForm.ifInterestinstrument12 = item.name }
          }
          if (level === 2) {
            if (item.id === id) { this.ruleForm.ifInterestinstrument1 = item.name }
          }
        })
      } catch (error) {
        this.projectAllList = []
      }
    },
    async handleCascaderChange (value) {
      this.ruleForm.ssId11 = value[0]
      this.ruleForm.ssId12 = value[1]
      this.ruleForm.ssId1 = value[2]
      // 反查仪器名称
      await this.getInstrumentName(0, 0, this.ruleForm.ssId11)
      await this.getInstrumentName(1, this.ruleForm.ssId11, this.ruleForm.ssId12)
      await this.getInstrumentName(2, this.ruleForm.ssId12, this.ruleForm.ssId1)
    },
    // 行业领域
    async getIndustryList () {
      const params = {
        parentId: 0
      }
      const { data } = await api.specialist.getIndustryClassifySelectByParentId(params)
      this.industrySectorList = data.data
    },
    async getIndustrySectorSelect (id) {
      this.industrySectorList.map(item => {
        if (item.id === id) {
          this.ruleForm.ifSpecializefield1 = item.name
        }
      })
    },
    goBack () {
      this.$router.go(-1)
    },
    async getDetail () {
      if (this.$route.query.id && this.$route.query.imshowId) {
        const params = {
          id: this.$route.query.id,
          imshowid: this.$route.query.imshowId
        }
        const { data } = await api.specialist.selectById(params)
        await this.getInstrumentViewsOne(parseInt(data.ssId11))
        await this.getInstrumentViewsTwo(parseInt(data.ssId11), parseInt(data.ssId12))
        this.ruleForm = data
        this.ruleForm.ssIdList = [1, 53, 519]
        this.ruleForm.imshowid = this.$route.query.imshowId
        this.defaultMSG = this.ruleForm.infoHtml
        this.dialogImageUrl.push({ name: 'avater', url: this.ruleForm.img })
        this.loading = false
      } else {
        this.ruleForm={
        adminID: getImShowId(),
        authorID: '', // 专家id
        ifName: '', // 专家姓名
        ifSex: null, // 性别
        img: '', // 专家头像
        ifEmail: '', // 电子邮箱
        ifMobile: '', // 手机号
        ifCompany: '', // 单位
        job: '', // 职位
        ssIdList: [], // 熟悉的仪器ssId集合
        ssId11: '', // 所熟悉的仪器一(一级)
        ssId12: '', // 所熟悉的仪器一(二级)
        ssId1: '', // 所熟悉的仪器一(三级)
        ifInterestinstrument11: '', // 所熟悉的仪器一(一级)名称
        ifInterestinstrument12: '', // 所熟悉的仪器一(二级)名称
        ifInterestinstrument1: '', // 所熟悉的仪器一(三级)名称
        fdId1: '', // 所熟悉的行业领域一
        ifSpecializefield1: '', // 所熟悉的行业领域一名称
        infoHtml: '', // 介绍（富文本）
        channel: 1, // 渠道（1-网络讲堂;2-我要测）
        type: 2 // 1-专家报告人；2-厂商报告人
      },
        this.loading = false
      }
    },
    // 根据1级回显2级仪器
    async getInstrumentViewsOne (id) {
      const params = {
        parentId: id
      }
      try {
        const { data } = await api.specialist.getPrincipleClassifySelectByLevel(params)
        if (data.data.length > 0) {
          for (let i = 0; i < data.data.length; i++) {
            data.data[i].value = data.data[i].id
            data.data[i].label = data.data[i].name
          }
        }
        this.projectAllList.map(item => {
          if (item.id === id) {
            item.children = data.data
          }
        })
        return this.projectAllList
      } catch (error) {
        this.projectAllList = []
      }
    },
    // 根据1级回显2级仪器
    async getInstrumentViewsTwo (oneId, twoId) {
      const params = {
        parentId: twoId
      }
      try {
        const { data } = await api.specialist.getPrincipleClassifySelectByLevel(params)
        if (data.data.length > 0) {
          for (let i = 0; i < data.data.length; i++) {
            data.data[i].value = data.data[i].id
            data.data[i].label = data.data[i].name
          }
        }
        this.projectAllList.map(item => {
          if (item.id === oneId) {
            item.children.map(childrenItem => {
              if (childrenItem.id === twoId) {
                childrenItem.children = data.data
              }
            })
          }
        })
        return this.projectAllList
      } catch (error) {
        this.projectAllList = []
      }
    }
  }
  }
  </script>
  
  <style lang="scss" scoped>
.hint {
  font-size: 14px;
  color: #999;
}
.alone-topBox-h3 {
  display: inline-block;
  vertical-align: middle;
  margin-left: 20px;
  font-size: 16px;
}
.topButton {
  position: absolute;
  right: 20px;
  top: 16px;
}
.flex_bt {
  justify-content: space-between;
}
.icon_right {
  font-weight: 600;
  color: #0c7ff2;
  cursor: pointer;
  font-size: 18px;
}
.add_zj{
  position: absolute;
  top: 0px;
  right: 0px;
}
  .author{
    height: 500px;
    overflow-y: auto;
  }
  // ::v-deep .author   .el-form-item__error{
  //   top: 36px !important;
  //     left: 0 !important;
  // }
  ::v-deep .el-form-item{
      margin-bottom: 0px !important;
  }
  // ::v-deep .el-form-item__error{
  //     top: 70% !important;
  //     left: 38px !important;
  // }
  // ::v-deep .error_title .el-form-item__error{
  //     top: 70% !important;
  //     left: 133px !important;
  // }
  ::v-deep .author   .el-form-item{
      margin-bottom: 22px !important;
  }
  ::v-deep .el-dialog__footer {
    padding-top: 0px;
    // border-top: 1px solid #e5eaf0;
  }
  ::v-deep .el-dialog__header {
    background: #f5f8fc;
    text-align: left;
    font-size: 16px;
    color: #202933;
    padding: 11px 16px;
  }
  ::v-deep .el-dialog__body {
    padding: 25px 25px 10px !important;
  }
  ::v-deep .el-dialog__title {
    font-size: 16px;
  }
  </style>